﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AutoMapper;

namespace UserGroupData
{
    public class SpeakerRepository : ISpeakerRepository
    {
        public SpeakerDTO GetSpeaker(int id)
        {
            using (var ctx = new UserGroupEntities())
            {
                var meeting = ctx.Speakers.Where(d => d.Id == id);
                var entity = meeting.FirstOrDefault();
                Mapper.CreateMap<Speaker, SpeakerDTO>();
                var dto = Mapper.Map<Speaker, SpeakerDTO>(entity);
                return dto;
            }
        }

        public List<SpeakerDTO> GetAllSpeakers()
        {
            using (var ctx = new UserGroupEntities())
            {
                var entities = ctx.Speakers.ToList();
                Mapper.CreateMap<Speaker, SpeakerDTO>();
                var dto = Mapper.Map<List<Speaker>, List<SpeakerDTO>>(entities);
                return dto;
            }
        }

        public int AddNewSpeaker(SpeakerDTO dto)
        {
            using (var ctx = new UserGroupEntities())
            {
                Mapper.CreateMap<SpeakerDTO, Speaker>();
                var entity = Mapper.Map<SpeakerDTO, Speaker>(dto);
                ctx.AddToSpeakers(entity);
                ctx.SaveChanges();
                return entity.Id;
            }
        }

        public void UpdateSpeaker(SpeakerDTO dto)
        {
            using (var ctx = new UserGroupEntities())
            {
                Mapper.CreateMap<SpeakerDTO, Speaker>();
                var entity = Mapper.Map<SpeakerDTO, Speaker>(dto);
                ctx.ApplyCurrentValues("Speakers", entity);
                ctx.SaveChanges();
            }
        }

        public void DeleteSpeakerDTO(int id)
        {
            using (var ctx = new UserGroupEntities())
            {
                Speaker dbDept = ctx.Speakers.First(d => d.Id == id);
                ctx.DeleteObject(dbDept);
                ctx.SaveChanges();
            }
        }
    }
}
